package com.wym.learning;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.MediaStore.Audio.Media;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;

import java.util.ArrayList;


public class MainActivity extends ActionBarActivity implements View.OnClickListener {
    private ArrayList<MusicModel> music_list = new ArrayList<MusicModel>();
    private ListView listView;
    private MusicAdapter adapter;
    private final String TAG = "MainActivity";

    private Intent serviceIntent;

    public static final String ACTION = "com.wym.action";
    public static final String UPDATE = "com.wym.update";
    private int current = 0;
    private ImageView start;
    private SeekBar seekBar;

    //当前播放进度
    private int currentProgress = 0;

    private MyReceiver myReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.background));
        setContentView(R.layout.activity_main);

        //上一曲
        ImageView front = (ImageView) findViewById(R.id.front);
        front.setOnClickListener(this);
        //继续暂停按钮
        start = (ImageView) findViewById(R.id.start);
        start.setOnClickListener(this);
        //下一曲
        ImageView next = (ImageView) findViewById(R.id.next);
        next.setOnClickListener(this);
        //进度条
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (currentProgress != progress) {
                    Intent i = new Intent(MainActivity.ACTION);
                    i.putExtra("control", 0x10013);
                    i.putExtra("progress", progress);
                    sendBroadcast(i);
                }

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        //歌曲列表
        listView = (ListView) findViewById(R.id.list);
        listView.setBackground(getResources().getDrawable(R.drawable.bg));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent send = new Intent(ACTION);
                send.putExtra("control", 0x10015);
                send.putExtra("current", position);
                sendBroadcast(send);
            }
        });

        //获取歌曲文件
        getMusicFiles();

        //开启一个服务
        serviceIntent = new Intent(this, PlayService.class);
        startService(serviceIntent);
        //动态注册broadcastReceiver
        myReceiver = new MyReceiver();
        IntentFilter filter = new IntentFilter(MainActivity.UPDATE);
        registerReceiver(myReceiver, filter);

    }

    @Override
    protected void onStart() {

        super.onStart();
    }

    //获取歌曲文件
    private void getMusicFiles() {
        String[] music = new String[]{Media._ID, Media.DISPLAY_NAME, Media.TITLE, Media.DURATION, Media.ARTIST, Media.DATA};
        Cursor cursor = getContentResolver().query(Media.EXTERNAL_CONTENT_URI, music, null, null, null);
        while (cursor.moveToNext()) {
            MusicModel model = new MusicModel();

            String[] names = cursor.getString(1).split("\\.");
            model.setName(names[0]);
            model.setTitle(cursor.getString(2));
            model.setDuration(cursor.getInt(3));
            model.setArtist(cursor.getString(4));
            model.setData(cursor.getString(5));
            if (model.getDuration() > 15000)
                music_list.add(model);

        }
        if (listView.getAdapter() == null) {
            adapter = new MusicAdapter();
            listView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
    }

    //广播接收器
    public class MyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int control = intent.getIntExtra("update", -1);
            switch (control) {
                case 0x1000://开始
                    start.setImageResource(R.drawable.star);
                    break;
                case 0x1003://停止
                    start.setImageResource(R.drawable.stop);
                    break;
                case 0x1005://进度
                    currentProgress = intent.getIntExtra("progress", 0);
                    seekBar.setProgress(currentProgress);
                    break;
                case 0x1006://进入时，继续上一次的播放进度
                    currentProgress = 0;
                    current = intent.getIntExtra("current", 0);
                    listView.setSelection(current);
                    adapter.notifyDataSetInvalidated();
                default:
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        Intent tmp = new Intent(ACTION);
        switch (v.getId()) {
            case R.id.front:
                Log.v(TAG, "上一曲");
                tmp.putExtra("control", 0x10010);
                break;
            case R.id.start:
                Log.v(TAG, "控制");
                tmp.putExtra("control", 0x10011);
                break;
            case R.id.next:
                Log.v(TAG, "下一曲");
                tmp.putExtra("control", 0x10012);
                break;
            default:
                break;
        }
        sendBroadcast(tmp);
    }

    private class MusicAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return music_list.size();
        }

        @Override
        public Object getItem(int position) {
            return music_list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            ViewHolder viewHolder = null;
            if (convertView == null) {
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.list_item, null);
                viewHolder.name = (TextView) convertView.findViewById(R.id.name);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            MusicModel model = music_list.get(position);

            viewHolder.name.setText(model.getName());
            if (position == current)
                convertView.setBackgroundColor(getResources().getColor(R.color.red));
            else
                convertView.setBackgroundColor(Color.TRANSPARENT);
            return convertView;
        }
    }

    private class ViewHolder {
        TextView singer;
        TextView name;
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.v(TAG, "onDestroy");
        //解除broadcast绑定
        unregisterReceiver(myReceiver);
        //停止服务
        stopService(serviceIntent);
        super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
